<%@include file="/header.jsp"%>
<%@include file="/login/checkLogin.jsp"%>
<%@ page import="dataGateway.ItemViewTable" %>
<%@ page import="domainLogic.ItemView" %>
<%@ page import="domainLogic.Bid" %>
<%
	String itemIdSt = request.getParameter("itemId");
if(itemIdSt == null)
{
	out.println(common.JspUtil.makeErrorMsg("Invalid request!", common.JspUtil.URL_DEFAULT));
	return;
}

if (request.getParameter("price") == null)
{
	out.println(common.JspUtil.makeErrorMsg("Please enter the price!"));
	return;
}

int itemId = Integer.parseInt(itemIdSt);
ItemView it = ItemViewTable.getInstance().getItem(itemId);

// Check whether the bid is closed or not
if(it.isBidClosed())
{
	out.println(common.JspUtil.makeErrorMsg("This bid is closed already.", common.JspUtil.URL_DEFAULT));
	return;
}

if(it.getUserId().equals(common.JspUtil.getLoggedInUserId(session)))
{
	out.println(common.JspUtil.makeErrorMsg("You are selling this item. The seller cannot join to bid."));
	return;
}
%>
<jsp:useBean id="newBid" class="domainLogic.Bid" scope="request" />
<jsp:setProperty name="newBid" property="*"/>
<%
newBid.setUserId(common.JspUtil.getLoggedInUserId(session));
newBid.setItemId(itemId);

if(it.nextBidPrice() > newBid.getPrice())
{
	out.println(common.JspUtil.makeErrorMsg("Price is too low, please check it again"));
	return;
}

if(it.getBuyoutprice() < newBid.getPrice() && it.getBuyoutprice() > 0)
{
	out.println(common.JspUtil.makeErrorMsg("The price exceeds Buy Out Price! You can buy it via Buy Out!"));
	return;
}

String bidtype = newBid.getPrice() == it.getBuyoutprice() ? "Buyout" : "Place Bid";
%>
<form method="post" action="addBidProcess.jsp">
<input type="hidden" name="itemId" value=<%=newBid.getItemId() %>>
<input type="hidden" name="userId" value=<%=newBid.getUserId() %>>
<input type="hidden" name="price" value=<%=newBid.getPrice() %>>

<h3><%=bidtype %> confirmation</h3>
<p>Please check details again.</p>
<table>
	<tr><td colspan="2"></td></tr>
	<tr>
		<td>Item</td>
		<td><%=it.getName() %></td>
	</tr>
	<tr>
		<td>Price</td>
		<td><%=newBid.getPrice() %>
		</td>
	</tr>
	<tr>
		<td>Your ID</td>
		<td><%=newBid.getUserId() %>
		</td>
	</tr>
	<tr><td></td>
		<td> <input type="submit" value="<%=bidtype %>">
		<input  type="button" value="Back" onClick="history.go(-1)"></td>
	</tr>
</table>
</form>
<%@include file="/footer.jsp"%>
